Inheritance (object-oriented programming)
part 15/28 · 45.4 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Inheritance vs subtyping
Inheritance is similar to but distinct from subtyping.cite-ref-cook90-4-1[4] Subtyping enables a given type to be substituted for another type or abstraction and is said to establish an is-a relationship between the subtype and some existing abstraction, either implicitly or explicitly, depending on language support. The relationship can be expressed explicitly via inheritance in languages that support inheritance as a subtyping mechanism. For example, the following C++ code establishes an explicit inheritance relationship between classes B and A, where B is both a subclass and a subtype of A and can be used as an A wherever a B is specified (via a reference, a pointer or the object itself).
class A {
public:
void DoSomethingALike() const {}
};
class B : public A {
public:
void DoSomethingBLike() const {}
};
void UseAnA(const A& a) {
a.DoSomethingALike();
}
void SomeFunc() {
B b;
UseAnA(b); // b can be substituted for an A.
}
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────